package com.miracle.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.miracle.common.utils.MyDateUtils;
import com.miracle.common.utils.StringUtils;
import com.miracle.model.EggItem;
import com.miracle.model.EggOrd;
import com.miracle.services.impls.EggItemListImpl;
import com.miracle.services.impls.EggOrdImpl;
import com.sun.istack.internal.logging.Logger;

@Controller
public class HomeController {
	Logger logger = Logger.getLogger(HomeController.class);

	@Autowired
	EggItemListImpl srvItem;

	@Autowired
	EggOrdImpl srvOrd;

	@RequestMapping(value = "/items", method = { RequestMethod.GET })
	protected ModelAndView showIndex(HttpServletRequest request) {
		ModelAndView mvAndView = new ModelAndView("itemList");
		List<Map<String, String>> list = srvItem.getDataListByPK(null);
		List<EggItem> listEgg = new ArrayList<EggItem>();
		for (Map<String, String> map : list) {
			EggItem item = new EggItem();

			item.setItmAmtJPY(map.get("itm_amt_jpy"));
			item.setItmAmtRMB(map.get("itm_amt_rmb"));
			item.setItmAmtSell(map.get("itm_amt_sell"));
			item.setItmId(map.get("itm_id"));
			item.setItmMrk(map.get("itm_mrk"));
			item.setItmNm(map.get("itm_nm"));
			listEgg.add(item);
		}
		mvAndView.addObject("listEgg", listEgg);
		return mvAndView;
	}

	@RequestMapping(value = "/saveItem", method = { RequestMethod.POST }, produces = "application/json;charset=utf-8")
	private String save(HttpServletRequest request, EggItem bean) {
		System.out.println(bean.getItmId());
		if (bean.getItmId().length() > 14) {
			System.out.println("主键字段超长");
			return "error";
		}
		if (bean.getItmMrk().length() > 20) {
			System.out.println("备注字段超长");
			return "error";
		}
		if (bean.getItmNm().length() > 20) {
			System.out.println("名称字段超长");
			return "error";
		}
		if (bean.getItmAmtJPY().length() > 10) {
			System.out.println("日元字段超长");
			return "error";
		}
		if (bean.getItmAmtRMB().length() > 10) {
			System.out.println("rmb字段超长");
			return "error";
		}
		if (bean.getItmAmtSell().length() > 10) {
			System.out.println("sell字段超长");
			return "error";
		}
		HashMap<String, String> map = new HashMap<>();
		map.put("itm_id", bean.getItmId());
		map.put("itm_nm", bean.getItmNm());
		map.put("itm_mrk", bean.getItmMrk());
		map.put("itm_amt_jpy", bean.getItmAmtJPY());
		map.put("itm_amt_rmb", bean.getItmAmtRMB());
		map.put("itm_amt_sell", bean.getItmAmtSell());
		srvItem.createOrSave(map, false);
		return "redirect:items";
	}

	@RequestMapping(value = "/createItem", method = { RequestMethod.POST }, produces = "application/json;charset=utf-8")
	private String create(HttpServletRequest request, EggItem bean) {
		System.out.println(bean.getItmId());
		HashMap<String, String> map = new HashMap<>();
		if (bean.getItmMrk().length() > 20) {
			System.out.println("备注字段超长");
			return "error";
		}
		if (bean.getItmNm().length() > 20) {
			System.out.println("名称字段超长");
			return "error";
		}
		if (bean.getItmAmtJPY().length() > 10) {
			System.out.println("日元字段超长");
			return "error";
		}
		if (bean.getItmAmtRMB().length() > 10) {
			System.out.println("rmb字段超长");
			return "error";
		}
		if (bean.getItmAmtSell().length() > 10) {
			System.out.println("sell字段超长");
			return "error";
		}
		map.put("itm_id", MyDateUtils.getCurrentDatetime(MyDateUtils.TimeFormat.LONG_DATE_PATTERN_14));
		map.put("itm_nm", bean.getItmNm());
		map.put("itm_mrk", bean.getItmMrk());
		map.put("itm_amt_jpy", bean.getItmAmtJPY());
		map.put("itm_amt_rmb", bean.getItmAmtRMB());
		map.put("itm_amt_sell", bean.getItmAmtSell());
		srvItem.createOrSave(map, true);
		return "redirect:items";
	}

	@RequestMapping(value = "/delItem", method = { RequestMethod.POST }, produces = "application/json;charset=utf-8")
	private String delete(HttpServletRequest request, EggItem bean) {
		System.out.println(bean.getItmId());
		if (bean.getItmId().length() > 14) {
			System.out.println("主键字段超长");
			return "error";
		}
		srvItem.delete(bean.getItmId());
		return "redirect:items";
	}

	@RequestMapping(value = "/orders", method = { RequestMethod.GET }, produces = "application/json;charset=utf-8")
	private ModelAndView getOrd(HttpServletRequest request, EggOrd bean) {
		ModelAndView mv = new ModelAndView("orders");
		List<EggOrd> listOrd = new ArrayList<EggOrd>();// 订单信息
		Map<String, List<EggOrd>> mapItemOrd = new HashMap<String, List<EggOrd>>();// 明细信息

		// db
		List<Map<String, String>> listAllOrd = srvOrd.getAllOrd();

		// 处理第一个查询
		for (Map<String, String> map : listAllOrd) {
			EggOrd ord = new EggOrd();
			EggOrd item = new EggOrd();
			// 订单
			ord.setOrdId(map.get("ord_id"));
			ord.setBuyerNm(map.get("buy_nm"));
			ord.setBuyerSrc(map.get("buy_src"));
			ord.setExpId(map.get("exp_id"));

			// 明细
			item.setItmNm(map.get("itm_nm"));
			item.setItmAmtJPY(map.get("itm_amt_jpy"));
			item.setItmAmtRMB(map.get("itm_amt_rmb"));
			item.setItmAmtSell(map.get("itm_amt_sell"));
			item.setItmCnt(map.get("itm_cnt"));
			item.setItmId(map.get("itm_id"));

			if (mapItemOrd.containsKey(ord.getOrdId())) {
				// 如果已经有明细，取出该订单号的明细，add明细
				mapItemOrd.get(ord.getOrdId()).add(item);
			} else {
				// 初始化
				listOrd.add(ord);
				List<EggOrd> listItemOrd = new ArrayList<EggOrd>();// 明细
				listItemOrd.add(item);
				mapItemOrd.put(ord.getOrdId(), listItemOrd);
			}
		}

		// //处理第二个查询
		// }
		mv.addObject("allOrd", listOrd);// 外层订单循环List<Bean>
		mv.addObject("itemOrd", mapItemOrd);// 内层订单物品循环Map<String, List<Bean>>
		// mv.addObject("allItem", listItem);//下拉键
		return mv;
	}

	@RequestMapping(value = "/saveOrd", method = { RequestMethod.POST }, produces = "application/json;charset=utf-8")
	private String saveOrd(HttpServletRequest request) {
		String ordId = request.getParameter("ordId");
		String expId = request.getParameter("expId");
		String itmIdsJson = request.getParameter("itmIdsJson");
		List<EggOrd> listUpdate = new ArrayList<>();
		if (ordId.length() > 14) {
			System.out.println("单号字段超长");
			return "error";
		}
		System.out.println(ordId);
		System.out.println(itmIdsJson);
		JSONArray array = JSONObject.parseArray(itmIdsJson);
		Iterator<Object> iterator = array.iterator();
		while (iterator.hasNext()) {
			JSONObject json = (JSONObject) iterator.next();
			EggOrd ord = new EggOrd();
			ord.setOrdId(json.getString("ordId"));
			ord.setItmCnt(json.getString("itmCnt"));
			ord.setItmId(json.getString("itmId"));
			listUpdate.add(ord);
		}
		Map<String, String> map = new HashMap<>();
		map.put("expId", expId);
		map.put("ordId", ordId);
		srvOrd.updateHead(map);
		srvOrd.batchSave(listUpdate);
		return "redirect:orders";
	}

	@RequestMapping(value = "/delOrdItem", method = { RequestMethod.POST }, produces = "application/json;charset=utf-8")
	private String delOrdItem(HttpServletRequest request, EggOrd bean) {
		if (bean.getOrdId().length() > 14) {
			System.out.println("单号字段超长");
			return "error";
		}
		if (bean.getItmId().length() > 14) {
			System.out.println("物品字段超长");
			return "error";
		}
		srvOrd.delete(bean.getOrdId(), bean.getItmId());
		return "redirect:orders";
	}

	@RequestMapping(value = "/wish", method = { RequestMethod.GET }, produces = "application/json;charset=utf-8")
	private ModelAndView queryItems(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("place");
		JSONArray jsonOut = new JSONArray();
		List<Map<String, String>> listAllItem = srvItem.getDataListByPK(null);
		for (Map<String, String> map : listAllItem) {
			JSONObject json = new JSONObject();
			json.put("itmId", map.get("itm_id"));
			json.put("itmNm", map.get("itm_nm"));
			json.put("itmAmtJPY", map.get("itm_amt_jpy"));
			json.put("itmAmtRMB", map.get("itm_amt_rmb"));
			json.put("itmAmtSell", map.get("itm_amt_sell"));
			jsonOut.add(json);
		}
		mv.addObject("allItems", jsonOut);
		return mv;
	}

	@RequestMapping(value = "/place", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json;charset=utf-8")
	private String placeOrd(HttpServletRequest request) {
		System.out.println(request.getSession().getAttribute("itms"));
		System.out.println(request.getSession().getAttribute("eggOrd"));
		EggOrd bean = (EggOrd) request.getSession().getAttribute("eggOrd");
		
		List<EggOrd> listCreate = new ArrayList<>();
		if (bean.getBuyerTel().length() > 13) {
			System.out.println("号码字段超长");
			return "error";
		}
		if (bean.getBuyerNm().length() > 20) {
			System.out.println("昵称字段超长");
			return "error";
		}
		if (bean.getBuyerSrc().length() > 1) {
			System.out.println("客源字段超长");
			return "error";
		}

		// db查价格
		List<Map<String, String>> list = srvItem.getDataListByPK(null);
		Map<String, HashMap<String, String>> mapAmt = new HashMap<>();//价格字典
		for (Map<String, String> map : list) {
			HashMap<String, String> mapTmp = new HashMap<>();
			mapTmp.put("itm_amt_jpy", map.get("itm_amt_jpy"));
			mapTmp.put("itm_amt_rmb", map.get("itm_amt_rmb"));
			mapTmp.put("itm_amt_sell", map.get("itm_amt_sell"));
			mapTmp.put("itm_nm", map.get("itm_nm"));
			mapAmt.put(map.get("itm_id"), mapTmp);
		}

		String ordId = MyDateUtils.getCurrentDatetime(MyDateUtils.TimeFormat.LONG_DATE_PATTERN_14);
		JSONArray jsonList = JSONArray.parseArray(request.getSession().getAttribute("itms").toString());
		for (Object object : jsonList) {
			JSONObject json = (JSONObject) object;
			EggOrd ord = new EggOrd();
			//head
			ord.setOrdId(ordId);
			ord.setBuyerNm(bean.getBuyerNm());
			ord.setBuyerSrc(bean.getBuyerSrc());
			ord.setBuyerTel(bean.getBuyerTel());
			
			//body
			ord.setItmId(json.getString("itmId"));
			ord.setItmCnt(json.getString("itmCnt"));
			ord.setItmNm(mapAmt.get(json.getString("itmId")).get("itm_nm"));
			ord.setItmAmtJPY(mapAmt.get(json.getString("itmId")).get("itm_amt_jpy"));
			ord.setItmAmtRMB(mapAmt.get(json.getString("itmId")).get("itm_amt_rmb"));
			ord.setItmAmtSell(mapAmt.get(json.getString("itmId")).get("itm_amt_sell"));
			listCreate.add(ord);
		}

		srvOrd.headInsert(bean.getBuyerNm(), bean.getBuyerSrc(), ordId, bean.getBuyerTel());
		srvOrd.batchInsert(listCreate);
		request.setAttribute("ordId", ordId);
		request.setAttribute("buyTel", bean.getBuyerTel());
		request.getSession().removeAttribute("eggOrd");
		request.getSession().removeAttribute("itms");
		return "express";
	}
	
	@RequestMapping(value = "/addAddr", method = { RequestMethod.POST }, produces = "application/json;charset=utf-8")
	private String addAddr(HttpServletRequest request, EggOrd bean) {
		request.getSession().setAttribute("flg", "error");
		if (StringUtils.isEmpty(bean.getOrdId()) || StringUtils.isEmpty(bean.getBuyerAddr()) || StringUtils.isEmpty(bean.getBuyerTel())) {
			System.out.println("参数为null");
			return "redirect:flg";
		}
		if (bean.getOrdId().length() > 14) {
			System.out.println("单号字段超长");
			return "redirect:flg";
		}
		if (bean.getBuyerAddr().length() > 100) {
			System.out.println("地址字段超长");
			return "redirect:flg";
		}
		if (bean.getBuyerTel().length() > 13) {
			System.out.println("手机字段超长");
			return "redirect:flg";
		}
		Map<String, String> map = new HashMap<>();
		map.put("ordId", bean.getOrdId());
		map.put("buyTel", bean.getBuyerTel());
		map.put("buyAddr", bean.getBuyerAddr());
		boolean res = srvOrd.updateHead(map);
		if(res) {
			request.getSession().setAttribute("flg", "success");
		}
		return "redirect:flg";
	}

	@RequestMapping(value = "/flg", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json;charset=utf-8")
	private ModelAndView endView(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();
		String view = "error";
		if("success".equals(request.getSession().getAttribute("flg"))){
			view = "success";
		}
		else if("error".equals(request.getSession().getAttribute("flg"))){
			view = "error";
		}
		mv.setViewName(view);
		request.getSession().removeAttribute("flg");
		return mv;
	}
	
	@RequestMapping(value = "/express", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json;charset=utf-8")
	private String order(HttpServletRequest request, EggOrd bean) {
		if(StringUtils.isEmpty(bean.getOrdId())) {
			if(bean == null || StringUtils.isEmpty(request.getParameter("itms"))) {
				return "redirect:flg";
			}
			request.getSession().setAttribute("eggOrd", bean);
			request.getSession().setAttribute("itms", request.getParameter("itms"));
			return "forward:place";
		}
		else{
			return "redirect:flg";
		}
	}
	

	@RequestMapping(value = "/ords", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json;charset=utf-8")
	private ModelAndView ords(HttpServletRequest request, EggOrd bean) {
		ModelAndView mv = new ModelAndView("ordersCustom");
		List<EggOrd> listOrd = new ArrayList<EggOrd>();// 订单信息
		Map<String, List<EggOrd>> mapItemOrd = new HashMap<String, List<EggOrd>>();// 明细信息

		// db
		List<Map<String, String>> listAllOrd = srvOrd.getAllOrd();

		// 处理第一个查询
		for (Map<String, String> map : listAllOrd) {
			EggOrd ord = new EggOrd();
			EggOrd item = new EggOrd();
			// 订单
			ord.setOrdId(map.get("ord_id"));
			String nm = map.get("buy_nm");
			if(nm.length() >= 2) {
				nm = nm.substring(0, 2) + "***";
			}
			ord.setBuyerNm(nm);
			ord.setBuyerSrc(map.get("buy_src"));
			String tel = map.get("buy_tel");
			ord.setBuyerTel(tel.substring(0, 3) + "*****" + tel.substring(8));
			ord.setExpId(map.get("exp_id"));

			// 明细
			item.setItmNm(map.get("itm_nm"));
			item.setItmAmtJPY(map.get("itm_amt_jpy"));
			item.setItmAmtRMB(map.get("itm_amt_rmb"));
			item.setItmAmtSell(map.get("itm_amt_sell"));
			item.setItmCnt(map.get("itm_cnt"));
			item.setItmId(map.get("itm_id"));

			if (mapItemOrd.containsKey(ord.getOrdId())) {
				// 如果已经有明细，取出该订单号的明细，add明细
				mapItemOrd.get(ord.getOrdId()).add(item);
			} else {
				// 初始化
				listOrd.add(ord);
				List<EggOrd> listItemOrd = new ArrayList<EggOrd>();// 明细
				listItemOrd.add(item);
				mapItemOrd.put(ord.getOrdId(), listItemOrd);
			}
		}

		mv.addObject("allOrd", listOrd);// 外层订单循环List<Bean>
		mv.addObject("itemOrd", mapItemOrd);// 内层订单物品循环Map<String, List<Bean>>
		return mv;
	}
}
